﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Scala.Compiler.Ast
{
    public class BlockStatement:Statement
    {
        private readonly Statement[] _stats;
        private readonly Statement _expr;

        public BlockStatement(Statement[] stats, Statement expr)
        {
            _stats = stats;
            _expr = expr;
        }

        public IList<Statement> Stats { get { return _stats; } }
        public Statement Expr { get { return _expr; } }
        public IList<Statement> Statements
        {
            get
            {
                List<Statement> t = new List<Statement>();
                foreach (Statement s in _stats) t.Add(s);
                t.Add(_expr);
                return t;
            }
        }

        public override void Walk(ScalaWalker walker)
        {
            if (walker.Walk(this))
            {
                if (_stats != null)
                {
                    foreach (Statement s in _stats) { s.Walk(walker); }
                }
                if (_expr != null) _expr.Walk(walker);
            }
            walker.PostWalk(this);
        }

        public override Microsoft.Scripting.Ast.Expression Reduce()
        {
            IList<Microsoft.Scripting.Ast.ParameterExpression> locals = new List<Microsoft.Scripting.Ast.ParameterExpression>();
            IList<Microsoft.Scripting.Ast.Expression> exprs = new List<Microsoft.Scripting.Ast.Expression>();
            
            foreach (var stat in Statements)
            {
                exprs.Add(stat.Reduce());
            }

            foreach (var variable in Scope.Variables)
            {
                if (!variable.Value.IsProperty && !variable.Value.IsParam) locals.Add(variable.Value.ParamExpression);
            }

            return Expression.Block(locals, exprs);
        }
    }
}
